package com.zxj.geekstudy.jvm;

import java.io.InputStream;
import java.lang.reflect.Method;

/**
 * 自定义一个 Classloader，加载一个 Hello.xlass 文件，执行 hello 方法，此文件内容是一个 Hello.class 文件所有字节（x=255-x）处理后的文件。
 */
public class CustomClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("Hello.xlass");){
            int length = inputStream.available();
            byte[] array = new byte[length];
            inputStream.read(array);
            for (int i = 0; i < array.length; i++) {
                array[i] = (byte) (255 - array[i]);
            }
            return defineClass(name, array, 0, array.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            Class helloClass = new CustomClassLoader().findClass("Hello");
            Object hello = helloClass.newInstance();
            Method[] methods = helloClass.getMethods();
            for (Method method : methods) {
                System.out.println(method.getName());
                if ("hello".equals(method.getName())) {
                    method.invoke(hello);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
